package com.jcark.utilscode.ext

import android.text.Editable
import android.text.InputFilter
import android.text.SpannableString
import android.text.Spanned
import android.text.SpannedString
import android.text.TextWatcher
import android.text.style.AbsoluteSizeSpan
import android.widget.EditText
import com.blankj.utilcode.constant.RegexConstants
import com.blankj.utilcode.util.RegexUtils

fun EditText.afterChange(callback: (String) -> Unit) {
    addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

        override fun afterTextChanged(s: Editable?) {
            callback.invoke(s.toString())
        }
    })
}

fun EditText.enter(callback: () -> Unit) {
    setOnEditorActionListener { v, actionId, event ->
        callback.invoke()
        true
    }
}

/**
 * 设置正则表达式，可设置最大个数
 * @param regEx 详情见[RegexConstants]
 */
fun EditText.setRegex(regEx: String, maxLength: Int? = null) {
    var filter = InputFilter { source, start, end, _, _, _ ->
        for (i in start until end) {
            if (RegexUtils.isRegex(source[i].toString(), regEx)) {
                return@InputFilter ""
            }
        }
        null
    }
    filters =
        if (maxLength ?: 0 > 0) arrayOf(filter, InputFilter.LengthFilter(maxLength!!)) else arrayOf(
            filter
        )
}

/**
 * 设置提示文本大小
 */
fun EditText.setHintTextSize(strHint: String, absoluteSize: Int = 15) {
    val spanStr = SpannableString(strHint)
    val ass = AbsoluteSizeSpan(absoluteSize, true)
    spanStr.setSpan(ass, 0, spanStr.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    hint = SpannedString(spanStr) // 一定要进行转换,否则属性会消失
}

/**
 * 设置只读
 */
fun EditText.setReadOnly(isReadOnly: Boolean = true) {
    isFocusable = !isReadOnly
    isFocusableInTouchMode = !isReadOnly
}

/**
 * 增加editText 输入监听
 * @param regex 用以匹配的正则表达式
 * @param replacement 替换匹配上的字符串
 */
fun setTextReplace(editText: EditText, regex: String, replacement: String) {
    editText.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            val editable: String = editText.text.toString()
            val str: String = RegexUtils.getReplaceAll(editable, regex, replacement)
            if (editable != str) {
                editText.setText(str)
                editText.setSelection(str.length)
            }
        }

        override fun afterTextChanged(s: Editable) {}
    })
}